package com.bishe.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bishe.entity.User;
import com.bishe.entity.query.UserQuery;
import com.bishe.entity.response.LoginInfo;
import com.bishe.entity.response.UserInfo;
import com.bishe.mapper.UserMapper;
import com.bishe.satoken.StpInterfaceImpl;
import com.bishe.service.UserService;
import com.bishe.util.LoginUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author wwz
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-03-04 13:57:33
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Resource
    private StpInterfaceImpl stpInterface;


    @Override
    public IPage<User> getPage(UserQuery query) {
        return page(query.toPage(), Wrappers.lambdaQuery(User.class)
                .like(StrUtil.isNotBlank(query.getPhone()),User::getPhone,query.getPhone())
                .like(StrUtil.isNotBlank(query.getNickName()),User::getNickName,query.getNickName()));
    }

    @Override
    public UserInfo login(LoginInfo loginInfo) {
        // 检查登录信息
        LoginUtils.checkLoginInfo(loginInfo);

        String userName = loginInfo.getUserName();
        String password = loginInfo.getPassword();

        // 登录用户查询
        User one = getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUserName, userName)
                .eq(User::getPwd, password),false);
        if (one == null) {
            return null;
        }

        StpUtil.login(one.getId());

        List<String> permissionCodes =
                stpInterface.getPermissionList(StpUtil.getLoginId(), "login");

        UserInfo userInfo = new UserInfo();
        userInfo.setId(one.getId());
        userInfo.setName(one.getUserName());
        userInfo.setToken(StpUtil.getTokenValue());
        userInfo.setType(one.getType());
        userInfo.setCode(permissionCodes);
        return userInfo;
    }
}




